package com.baizhi.controller;

import com.baizhi.entity.iPhone;
import com.baizhi.service.iPhoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class iPhoneController {
    @Autowired
    private iPhoneService iPhoneService;

    @GetMapping("/iphones")
    public Map showAll(@RequestParam(defaultValue = "1")Integer page, @RequestParam(defaultValue = "5")Integer limit){
        Map map = new HashMap();
        List<iPhone> iPhones = iPhoneService.selectAll(page, limit);
        int totalRows = iPhoneService.totalRows();
        map.put("count",totalRows);
        map.put("data",iPhones);
        map.put("code",0);

        return map;
    }
    @PutMapping("/iphones")
    public Map update(@RequestBody iPhone iPhone){
        Map map = new HashMap();
        try {
            iPhoneService.update(iPhone);
            map.put("status","success");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status","error");
        }
        return map;
    }
    @DeleteMapping("/iphones/{id}")
    public Map deleteById(@PathVariable Integer id){
        Map map = new HashMap();
        try {
            iPhoneService.deleteById(id);
            map.put("status","success");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status","error");
        }
        return map;
    }
    @DeleteMapping("/iphones")
    public Map deleteMany(@RequestBody List<Integer> ids){
        Map map = new HashMap();
        try {
            iPhoneService.deleteMany(ids);
            map.put("status","success");
        } catch (Exception e) {
            map.put("status","error");
            e.printStackTrace();
        }
        return map;
    }
    @PostMapping("/iphones")
    public Map insert(@RequestBody iPhone iPhone){
        Map map = new HashMap();
        try {
            iPhoneService.insert(iPhone);
            map.put("status","success");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status","error");
        }

        return map;
    }
}
